<?php
require_once('lyfunctions.php');
$src=$_REQUEST['src'];
if(!$src) {
  $src=$_REQUEST['gabc'];
}
if($_REQUEST['type'] == 'modern') {
  $type = 'modern';
  $extension = 'ly';
  $src = getLy($_REQUEST,true);
} else {
  $type = 'square';
  $extension = 'gabc';
}
$engravings = "engravings/$type";
$graphics = "graphics/$type";
$filename = $_REQUEST['filename'];
if(!$filename) {
  $filename = $_REQUEST['name'];
}
$filename = normalizeFilename($filename);
$dir = $_REQUEST['dir'];

$format=$_REQUEST['fmt'];
$width=$_REQUEST['width'];
$height=$_REQUEST['height'];
$spacing=$_REQUEST['spacing'];
$croppdf=true;
if($_REQUEST['croppdf']=='false'){
  $croppdf=false;
}
if($width==''){
  $width='5';
}
if($height==''){
  $height='11';
}
ini_set('magic_quotes_runtime', 0);
if($format==''){
  $format='png';
  $fmtmime='image/png';
} else {
  $fmtmime='application/pdf';
}
if($src!='') {
  $ofilename = $filename;
  $odir = $dir;
  if($type=='square') {
    $theader = substr($src,0,strpos($src,'%%'));
    $header = array();
    $pattern = '/(?:^|\\n)([\w-_]+):\s*([^;\\r\\n]+)(?:;|$)/i';
    $offset = 0;
    if(preg_match_all($pattern, $theader, $matches)>0){
      foreach($matches[1] as $key => $value){
        $header[$value] = $matches[2][$key];
      }
    }
    $odir = $header['office-part'];
    if(!$ofilename) {
      $ofilename = $header['name'];
      if($ofilename=='') {
        $ofilename='Untitled';
        $odir='sandbox';
      }
    }
  }

  if($odir == ''){
    $odir='sandbox';
  } else if(!is_dir("library/$engravings/$odir")){
    header("Content-type: text/plain");
    echo "The directory library/$engravings/$odir does not exist.  Please create it manually if this is the directory you intended.";
    return;
  }
  
  $tmpfname = str_replace('\'','',"tmp/$ofilename");
  $namegabc = "$tmpfname.gabc";
  $namegtex = "$tmpfname.tex";
  $nametex = "$tmpfname.main.tex";
  $namedvi = "$tmpfname.main.dvi";
  $namepdf = "$tmpfname.main.pdf";
  $namelog="$tmpfname.main.log";
  $nameaux="$tmpfname.main.aux";
  $namely = "$tmpfname.ly";
  $nameps = "$tmpfname.ps";
  
  $find = array('\'',' ');
  $replace = array('\\\'','\\ ');
  $tmpfnameS = str_replace($find,$replace,$tmpfname);
  $namegabcS = str_replace($find,$replace,$namegabc);
  $namegtexS = str_replace($find,$replace,$namegtex);
  $nametexS = str_replace($find,$replace,$nametex);
  $namedviS = str_replace($find,$replace,$namedvi);
  $namepdfS = str_replace($find,$replace,$namepdf);
  $namelogS = str_replace($find,$replace,$namelog);
  $nameauxS = str_replace($find,$replace,$nameaux);
  $namelyS = str_replace($find,$replace,$namely);
  $namepsS = str_replace($find,$replace,$nameps);
  
  $deletepdf = ($_REQUEST['save']!='true' or $ofilename=='Untitled');
  $finalpdf = ($deletepdf?'tmp/tmp.':"library/$engravings/$odir/")."$ofilename.pdf";
  $finalpng = (($deletepdf||$type=='modern')?'':"library/$graphics/$odir/$ofilename.png");
  $finalpdfS = str_replace($find,$replace,$finalpdf);
  $finalpngS = str_replace($find,$replace,$finalpng);
  
  if($type=='modern') {
    saveLy($_REQUEST);
    $namesrc = $namely;
    $width = 72 * $width;
    $height = 72 * $height;
    // write out ly file
    file_put_contents($namely, $src);
    
    // run lilypond
    exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
    // Run gs on it.
    exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dDEVICEWIDTHPOINTS=$width -dDEVICEHEIGHTPOINTS=$height -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=\"{$namepdf}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
    if($lyRetVal || !file_exists($nameps)){
      @header("Content-type: text/plain");
      echo implode("\n",$lyOutput);
      return;
    }
    if($gsRetVal || !file_exists($namepdf)){
      @header("Content-type: text/plain");
      echo implode("\n",$lyOutput);
      echo "\n\n";
      echo implode("\n",$gsOutput);
      return;
    }
  } else {
    $namesrc = $namegabc;
    $spacingcmd = '';
    if($spacing!=''){
      //$spacingcmd = "\\GreLoadSpaceConf{{$spacing}}";
      $spacingcmd = "\\input gsp-$spacing.tex\\greadaptconfvalues\\gresetverticalspaces\\global\\divide\\greadditionallineswidth by \\grefactor%";
    }
    $italicline = $header['commentary'];
    $commentcmd = '';
    $usernotesline = $header['user-notes'];
    if($usernotesline != '' or $italicline != ''){
      $commentcmd = "\\dualcomment{{$usernotesline}}{{$italicline}}";
    }
    $annotation = $header['annotation'];
    $annotcmd = '';
    $annotsuffix='';
    if($annotation != '') {
      if(preg_match('/[a-g]\d?\*?\s*$/',$annotation, $match)){
        $annotsuffix=$match[0];
        $annotation = substr($annotation,0,strlen($annotation) - strlen($annotsuffix));
      }
      $annotation = preg_replace_callback(
        '/\b[A-Z\d]+\b/',
        create_function(
          '$matches',
          'return strtolower($matches[0]);'
        ),
        $annotation
      );
      $annothelper = "\\fontsize{12}{12}\\selectfont{\\textsc{{$annotation}}$annotsuffix}";
      $annotcmd = "\\gresetfirstlineaboveinitial{{$annothelper}}{{$annothelper}}";
    }
    if($annotcmd != ''){
      $annotwidthcmd = <<<EOF
\\newlength{\\annotwidth}
\\settowidth{\\annotwidth}{{$annothelper}}
\\newlength{\\spacewidth}
%\\setlength{\\spacewidth}{0.6em plus 0em minus 0em}
\\setlength{\\spacewidth}{0.4\\annotwidth}
\\newlength{\\initwidth}
\\settowidth{\\initwidth}{\LARGE I}
\\addtolength{\\spacewidth}{-0.3\\initwidth}
\\setspaceafterinitial{\\spacewidth}
\\setspacebeforeinitial{\\spacewidth}
EOF;
    }
    $annotwidthcmd=<<<EOF
\\setspaceafterinitial{2.2mm plus 0em minus 0em}
\\setspacebeforeinitial{2.2mm plus 0em minus 0em}
EOF;
    $pwidth=$width+1;
    $papercmd=<<<EOF
%\\usepackage{vmargin}
%\\setpapersize{custom}{{$pwidth}in}{{$height}in}
%\\setmargnohfrb{0.5in}{0.5in}{0.5in}{0.5in}
\\usepackage[papersize={{$pwidth}in,{$height}in},margin=0.5in]{geometry}
\\special{ pdf: pagesize width {$pwidth}truein height {$height}truein}
EOF;
    
  // write out gabc
    $handle = fopen($namegabc, 'w');
    if(!$handle){
      header("Content-type: text/plain");
      echo "Unable to create file $namegabc";
      return;
    }
    fwrite($handle, "\xEF\xBB\xBF$src");
    fclose($handle);
  // Write out a template main.tex file that includes the score just outputted.
    $handle = fopen($nametex, 'w');
    fwrite($handle, <<<EOF
\\documentclass[10pt]{article}
$papercmd
%\\usepackage{fullpage}
\\usepackage{color}
\\usepackage{gregoriotex}
\\usepackage{verse}
\\usepackage[utf8]{luainputenc}
\\usepackage{soul}
\\usepackage{fontspec}
\\textwidth {$width}in
\\pagestyle{empty}
\\begin{document}
\\setmainfont[Extension=.otf,BoldFont=*-Smbd,ItalicFont=*-It,BoldItalicFont=*-SmbdIt]{GaramondPremrPro}
\\newfontfamily\\versiculum{Versiculum}
\\gresetstafflinefactor{13}
\\def\\greinitialformat#1{%
{\\fontsize{38}{38}\\selectfont #1}}
\\gdef\\grelowchoralsignstyle#1{{\\fontsize{8}{8}\\selectfont #1}}
\\gdef\\grehighchoralsignstyle#1{{\\fontsize{8}{8}\\selectfont #1}}
\\def\\greabovelinestextstyle#1{\\hspace*{-5pt}\\small\\textit{#1}}


\\def\\dualcomment#1#2{%
  {\\fontsize{10}{10}\\selectfont
  \\setlength{\\parindent}{0pt}%
  \\vbox{\\textit{#1 \\hfill #2}}%
  \\vspace{0.25em}%
  \\relax}%
}
\\def\\grestar{%
  *%
  \\relax%
}
\\def\\Abar{%
  {\\versiculum a}%
  \\relax%
}

\\def\\Rbar{%
  {\\versiculum r}%
  \\relax%
}

\\def\\Vbar{%
  {\\versiculum v}%
  \\relax%
}
\\def\\gretranslationformat#1{%
  \\fontsize{10}{10}\\selectfont\\it{#1}%
  \\relax %
}
\\def\\pdfliteral#1{%
  \\relax%
}
\\def\\UseAlternatePunctumCavum{%
\\gdef\\grepunctumcavumchar{\\gregoriofont\\char 75}%
\\gdef\\grelineapunctumcavumchar{\\gregoriofont\\char 76}%
\\gdef\\grepunctumcavumholechar{\\gregoriofont\\char 78}%
\\gdef\\grelineapunctumcavumholechar{\\gregoriofont\\char 80}%
\\relax %
}
$annotcmd \\nopagebreak\\

$commentcmd
\\nopagebreak\\setgrefactor{17}
{\\fontsize{10}{10}\\selectfont
$annotwidthcmd
\\gretranslationheight = 0.1904in
\\grespaceabovelines=0.1044in
$spacingcmd
\\large
\\nopagebreak\\UseAlternatePunctumCavum{\\includescore{"$namegtex"}}
\\vspace{0in}%
}
\\end{document}
EOF
      );
  // run gregorio
    exec("/home/sacredmusic/bin/gregorio $namegabcS 2>&1", $gregOutput, $gregRetVal);
    $gregTexContent = file_get_contents($namegtex);
    $gregTexContent = preg_replace('/(\n[^\n]*)\\\\greblockcustos([^\n]*\n)/',"\n\\greblockcustos".'$1$2',$gregTexContent);
    ////$gregTexContent = preg_replace('/(\n[^\n]*\\\\grelastofline[^\n]*\n)/',"\n",$gregTexContent);
    $gregTexContent = preg_replace('/(\\\\greblockcustos[^.]*?\\\\gresyllable{[^}]*}{[^}]*}{[^}]*}{)0(})/','${1}1$2',$gregTexContent);
    file_put_contents($namegtex, $gregTexContent);
  // Run lualatex on it.
    exec("export HOME=/home/sacredmusic && export TEXMFCNF=.: && /home/sacredmusic/texlive/2013/bin/i386-linux/lualatex -output-directory=tmp -interaction=batchmode $nametexS 2>&1", $lualatexOutput, $lualatexRetVal);
  // Run lamed on it.
  //  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && export TEXMFCNF=.: && lamed -output-directory=tmp -interaction=batchmode $nametexS 2>&1", $lamedOutput, $lamedRetVal);
  // Run dvipdfm on the .dvi
  //  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && dvipdfm -o $namepdfS $namedviS 2>&1", $dvipdfmOutput, $dvipdfmRetVal);
    if($gregRetVal){
      header("Content-type: text/plain");
      echo implode("\n",$gregOutput);
      return;
    }
    if($lualatexRetVal){
      header("Content-type: text/plain");
      echo implode("\n",$gregOutput);
      echo "\n\n";
      echo implode("\n",$lualatexOutput);
      return;
    }
  }
// Copy the pdf into another directory, or upload to an FTP site.
  if($croppdf) {
    exec("pdfcrop $namepdfS $namepdfS 2>&1", $croppdfOutput, $croppdfRetVal);
    if($croppdfRetVal){
      header("Content-type: text/plain");
      echo implode("\n",$croppdfOutput);
      return;
    }
  }
  if($finalpng) {
    $dir = dirname($finalpng);
    if(!file_exists($dir)) {
      mkdir($dir, 0777, true);
    }
    //set_time_limit(0);
    exec("nohup convert -density 1200 $namepdfS -append -resize 25% -limit memory 128 -limit map 256 png:$finalpngS >/dev/null 2>/dev/null </dev/null &");
  }
  //rename($namepdf,$finalpdf);
  //Instead of just renaming it, let's subset the fonts:
  exec("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=$finalpdfS $namepdf");
  header("Content-type: $fmtmime");
  if($_REQUEST['save']!='true') {
    if($format=='pdf'){
      //passthru("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=- $finalpdfS");
      $handle = fopen($namepdf, 'r');
      fpassthru($handle);
      fclose($handle);
    } else {
      passthru("convert -density 480 $finalpdfS +append -resize 25% -limit memory 128 -limit map 256 $format:-");
    }
  }
  //@unlink($namepdf);
  @unlink($namedvi);
  @unlink($nametex);
  @unlink($nameaux);
  @unlink($namelog);
  @unlink($nameps);
  if($ofilename != 'gabc') {
    @unlink($namegtex);
  }
  if($deletepdf){
    @unlink($finalpdf);
    //@unlink($namely);
  }
  @rename($namesrc,"library/$engravings/$odir/$ofilename.$extension");
} else {
  header("Content-type: text/plain");
  echo "Error: No source file given.";
}
?>